import axios from 'axios';
import { toast } from '~/composables/util'
import { getToken } from '~/composables/auth'
import { useAuthStore } from '~/stores/authStore'

const service = axios.create({
    baseURL:'http://127.0.0.1:8999',
})

// 添加请求拦截器
service.interceptors.request.use(function (config) {

    const token = getToken()
    if(token){
        config.headers["Authorization"] = `Bearer ${token}`
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(function (response) {
    if(response?.data?.code === 401){
        toast(response?.data?.msg || "登录失效")
        const authStore = useAuthStore();
        authStore.logout();
        location.reload();
    }
    return response;
})

export default service
